<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麥當苗兒 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Model;
use Think\Model;

/**
 * 用戶模型
 * @author 麥當苗兒 <zuojiazi@vip.qq.com>
 */

class MemberModel extends Model {

    protected $_validate = array(
        array('nickname', '1,16', '昵稱長度為1-16個字符', self::EXISTS_VALIDATE, 'length'),
        array('nickname', '', '昵稱被占用', self::EXISTS_VALIDATE, 'unique'), //用戶名被占用
    );

    public function lists($status = 1, $order = 'uid DESC', $field = true){
        $map = array('status' => $status);
        return $this->field($field)->where($map)->order($order)->select();
    }

    /**
     * 登錄指定用戶
     * @param  integer $uid 用戶ID
     * @return boolean      ture-登錄成功，false-登錄失敗
     */
    public function login($uid){
        /* 檢測是否在當前應用註冊 */
        $user = $this->field(true)->find($uid);
        if(!$user || 1 != $user['status']) {
            $this->error = '用戶不存在或已被禁用！'; //應用級別禁用
            return false;
        }

        //記錄行為
        action_log('user_login', 'member', $uid, $uid);

        /* 登錄用戶 */
        $this->autoLogin($user);
        return true;
    }

    /**
     * 註銷當前用戶
     * @return void
     */
    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
    }

    /**
     * 自動登錄用戶
     * @param  integer $user 用戶信息數組
     */
    private function autoLogin($user){
        /* 更新登錄信息 */
        $data = array(
            'uid'             => $user['uid'],
            'login'           => array('exp', '`login`+1'),
            'last_login_time' => NOW_TIME,
            'last_login_ip'   => get_client_ip(1),
        );
        $this->save($data);

        /* 記錄登錄SESSION和COOKIES */
        $auth = array(
            'uid'             => $user['uid'],
            'username'        => $user['nickname'],
            'last_login_time' => $user['last_login_time'],
        );

        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));

    }

    public function getNickName($uid){
        return $this->where(array('uid'=>(int)$uid))->getField('nickname');
    }

}